# ------------------------------- Base Setting BEGIN --------------------------------
# 查看PowerShell版本： $psversiontable
# 查看PowerShell版本： $psversiontable
#$ps_version = (Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion
# echo "[Debug] PowerShell Version = $ps_version"

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
chcp 65001 | Out-Null   # 将控制台的活动代码页设置为UTF-8

## ------------- 变量设置 ------------------------------------------------------------
$OsVersion = 0;
# 获取操作系统信息
$os = Get-CimInstance -ClassName Win32_OperatingSystem
$version = [version]$os.Version
# Windows 7 对应版本号为 6.1.*（例如 6.1.7601）。
# Windows 10/11 对应版本号为 10.0.*（例如 10.0.19045）。
# 判断系统版本
# 判断系统版本
if ($version.Major -eq 6) {
    switch ($version.Minor) {
        1 { # 6.1.*
            # Write-Output "Windows 7" 
            $OsVersion = 7;
        }       
        2 { # 6.2.*
            # Write-Output "Windows 8" 
            $OsVersion = 8;
        }       
        3 { # 6.3.*
            # Write-Output "Windows 8.1" 
            $OsVersion = 8.1;
        }    
        default { 
            # Write-Output "其他 Windows 版本: $($os.Caption)" 
            $OsVersion = 0;
        }
    }
} elseif ($version.Major -eq 10) {
    # 通过构建号区分 Win10 和 Win11
    if ($version.Build -ge 22000) {          # Win11 构建号 ≥ 22000
        # Write-Output "Windows 11"
        $OsVersion = 11;
    } else {                                 # Win10 构建号 < 22000
        # Write-Output "Windows 10"
        $OsVersion = 10;
    }
} else {
    # Write-Output "未知系统: $($os.Caption)"
    $OsVersion = 0;
}

## 
# $env:LESSCHARSET="utf-8" # 设置字符集
$env:PATHEXT += ";.py"   # Python 直接执行

# ------------------------------- Base Setting END --------------------------------

#-------------------------------    Functions BEGIN   -------------------------------
## 函数 检查程序命令安装
function which ($command) {
    Get-Command -Name $command -ErrorAction SilentlyContinue |
      Select-Object -ExpandProperty Path -ErrorAction SilentlyContinue
}

# 函数 添加系统环境变量
Function Add-EnvVars($AddEnvName,$AddEnvVal,$AddEnvClass) {
                                            # Process 、User 、Machine
    # 获取原来的环境变量
    $OrgPathParts = [System.Environment]::GetEnvironmentVariable("${AddEnvName}", "${AddEnvClass}")
    $PathParts = $OrgPathParts -Split ";"
    # Write-Host "[Debug] $PathParts"; # 打印信息
    if($PathParts -contains $AddEnvVal) { # 已存在了
        # -contains操作符确实很强大，但是很遗憾，它不能在指定字符串中包含通配符。如果想使用通配符进行查找数组元素，则可以使用-like操作符。
        Write-Host "[Debug] $PathParts  exist $AddEnvVal"; # 打印信息
    } else { # 不存在
        # Write-Host "[INFO] $AddEnvName isn't exist $AddEnvVal"; # 打印信息
        $NewPathParts = $PathParts + $AddEnvVal
        # Write-Host "[INFO] PathParts = $PathParts "; # 打印信息
        $NewPath = $NewPathParts -Join ";"
        # Write-Host "[INFO] NewPath == $NewPath  "; # 打印信息
        # [System.Environment]::SetEnvironmentVariable("${AddEnvName}", "${AddEnvVal}",  "${AddEnvClass}")
        [System.Environment]::SetEnvironmentVariable("${AddEnvName}", "${NewPath}",  "${AddEnvClass}")
        # [System.Environment]::SetEnvironmentVariable("${AddEnvName}", "${NewPath}",  "Machine") # 系统环境变量无法使用脚本写入 ，提示不允许所请求的注册表访问权。”
        # 添加完再次查询
        $PathParts = [System.Environment]::GetEnvironmentVariable("${AddEnvName}", "${AddEnvClass}") -Split ";"
        Write-Host "[INFO] $PathParts"; # 打印信息
    }
}
# 函数 检查并添加系统环境变量
Function Check-And-Add-USerEnvVars($TargetEnvPath){
    if(Test-Path -Path $TargetEnvPath) {# 文件夹存在
        # Write-Host "[INFO] $TargetEnvPath is exist."; # 打印信息
        if(-Not ($env:PATH.Contains("$TargetEnvPath"))) { # 不存在该环境变量
            Add-EnvVars "PATH" "$TargetEnvPath" "User";
        } else {
            # 
        }
    } else { # 文件夹不存在
        # 
        Write-Host "[INFO] $TargetEnvPath is not exist."; # 打印信息
    }
}

#-------------------------------    Functions END   ---------------------------------

#-------------------------------    ENV BEGIN   -------------------------------------
# 检查添加环境变量
Check-And-Add-USerEnvVars "C:\Tools\bin"  
Check-And-Add-USerEnvVars "C:\Tools\PSTools"
# Check-And-Add-USerEnvVars "${env:USERPROFILE}\Documents\XWorkSpaces\my-windows-config\scripts\fsshscp"
# Check-And-Add-USerEnvVars "${env:USERPROFILE}\Documents\XWorkSpaces\my-windows-config\scripts\bin"

# Write-Host "This is Microsoft.PowerShell_profile.ps1"
# Write-Host "-1--- PSScriptRoot = $PSScriptRoot --------"
$ProjectRoot = Split-Path -Path $PSScriptRoot # 获取上级父目录地址
# Write-Host "-2--- ProjectRoot = $ProjectRoot --------"
Check-And-Add-USerEnvVars "${ProjectRoot}\scripts\fsshscp"
Check-And-Add-USerEnvVars "${ProjectRoot}\scripts\bin"
Check-And-Add-USerEnvVars "C:\Program Files\FreeFileSync"
Check-And-Add-USerEnvVars "C:\Program Files (x86)\Neat Download Manager"

#-------------------------------    ENV END   ---------------------------------------



#------------------------------- Import Modules BEGIN -------------------------------
# --- 引入 posh-git  ------------------------------------------------
## 安装 Install-Module posh-git -Scope CurrentUser
## 导入模块posh-git
Import-Module posh-git
## 配置
# (& "$anaconda_insatll_path" "shell.powershell" "hook") | Out-String | ?{$_} | Invoke-Expression
$GitPromptSettings.DefaultPromptAbbreviateHomeDirectory = $true

$GitPromptSettings.DefaultPromptPrefix.ForegroundColor = [ConsoleColor]::Magenta
$GitPromptSettings.BeforePath = '['
$GitPromptSettings.AfterPath = ']'
$GitPromptSettings.DefaultPromptBeforeSuffix.Text = "`n" 
$GitPromptSettings.BeforePath.ForegroundColor = 'Green'
$GitPromptSettings.AfterPath.ForegroundColor = 'Green'

# $GitPromptSettings.DefaultPromptSuffix = ' $((Get-History -Count 1).id + 1)$(" PS> " * ($nestedPromptLevel + 1)) '
$ps_version = (Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion
# if ($OsVersion -eq 7) { # 如果当前宿主机是window7系统
#     $GitPromptSettings.DefaultPromptPrefix.Text = "$env:USERNAME $(Get-Date -f 'MM-dd HH:mm:ss')"
#     if (Get-Command python -ErrorAction SilentlyContinue) { # 修正 Python 版本获取（原命令有误）
#         $pyVer = (python --version) -replace '^Python\s*' 
#         $GitPromptSettings.DefaultPromptSuffix = "[$pyVer]-[$((Get-History -Count 1).id + 1)] $("PS-$ps_version > " * ($nestedPromptLevel + 1)) "
#     } else { 
#         $GitPromptSettings.DefaultPromptSuffix = "[$((Get-History -Count 1).id + 1)]$("PS-$ps_version > " * ($nestedPromptLevel + 1)) "
#     }
# } else { 
    function global:prompt {
        # 获取 Python 版本
        $pyVersion = ""
        if (Get-Command python -ErrorAction SilentlyContinue) {
            $verOutput = python --version 2>&1
            if ($verOutput -match 'Python (\d+\.\d+\.\d+)') {
                $pyVersion = "[P$($matches[1])] "
            }
        }

        # 获取 node.js 版本
        $nodeVersion = ""
        if (Get-Command node -ErrorAction SilentlyContinue) {
            $verOutput = node -v 2>&1
            if ($verOutput -match 'v(\d+\.\d+\.\d+)') {
                $nodeVersion = "[N$($matches[1])] "
            }
        }
        
        # 创建带颜色的部分
        # $date = Get-Date -f "MM-dd HH:mm:ss"
        $date = Get-Date -f "HH:mm:ss"
        $currentPath = (Get-Location).Path
        if ($currentPath.StartsWith($HOME)) {
            $currentPath = "~" + $currentPath.Substring($HOME.Length)
        }
        # 构建提示符:样式1
        # Write-Host "$env:USERNAME " -NoNewline -ForegroundColor Magenta
        # Write-Host "$date " -NoNewline -ForegroundColor Green
        # Write-Host "[" -NoNewline -ForegroundColor Yellow
        # # Write-Host (Get-Location) -NoNewline -ForegroundColor Yellow
        # Write-Host $currentPath -NoNewline -ForegroundColor Yellow
        # Write-Host "] " -NoNewline -ForegroundColor Yellow
        # Write-Host (Write-VcsStatus) -NoNewline -ForegroundColor Green 
        # Write-Host "`r`n$pyVersion" -NoNewline -ForegroundColor Blue
        # Write-Host "[$((Get-History -Count 1).id + 1)] " -NoNewline -ForegroundColor yellow
        # Write-Host "PS-$ps_version >" -NoNewline -ForegroundColor White

        # 构建提示符:样式2
        Write-Host "PS-$ps_version " -NoNewline -ForegroundColor White
        Write-Host "$env:USERNAME " -NoNewline -ForegroundColor Magenta
        Write-Host "$date " -NoNewline -ForegroundColor Green
        Write-Host "$pyVersion" -NoNewline -ForegroundColor Blue
        Write-Host "$nodeVersion" -NoNewline -ForegroundColor Blue
        Write-Host "[" -NoNewline -ForegroundColor Yellow
        # Write-Host (Get-Location) -NoNewline -ForegroundColor Yellow
        Write-Host $currentPath -NoNewline -ForegroundColor Yellow
        Write-Host "] " -NoNewline -ForegroundColor Yellow
        Write-Host (Write-VcsStatus) -NoNewline -ForegroundColor Green  
        Write-Host "`r`n" -NoNewline -ForegroundColor Blue
        Write-Host "$((Get-History -Count 1).id + 1) >" -NoNewline -ForegroundColor White
        return " "
    # }

}

# --- posh-git  -----------------------------------------------------

# --- 引入 ps-read-line ----------------------------------------------
Import-Module PSReadLine
# 安装： Install-Module -Name PSReadLine -AllowClobber -Force
# Import-Module PSReadLine
# 启用预测 IntelliSense 
#（预测性 IntelliSense 是对 Tab 键补全概念的补充，可帮助用户成功补全命令。 它使用户能够基于用户的历史记录和其他特定于域的插件中的匹配预测来发现、编辑和执行完整命令。）
#Set-PSReadLineOption -PredictionSource History

# PSReadLine 配置
#Get-PSReadLineOption         # 显示所有可以配置的选项
#Get-PSReadLineKeyHandler     # 显示所有可以配置的快捷键
Remove-PSReadlineKeyHandler 'Ctrl+r'                                   # 禁用默认按键
# 自定义键绑定
# Set-PSReadLineOption -PredictionSource History                         # 设置预测文本来源为历史记录
Set-PSReadLineOption -HistorySearchCursorMovesToEnd                    # 每次回溯输入历史，光标定位于输入内容末尾
Set-PSReadlineKeyHandler -Key Tab -Function Complete                   # Tab自动补全
Set-PSReadLineKeyHandler -Key "Tab" -Function MenuComplete             # 设置 Tab 为菜单补全和 Intellisense
# Set-PSReadLineKeyHandler -Key "Ctrl+d" -Function MenuComplete
# Set-PSReadlineKeyHandler -Key "Ctrl+d" -Function ViExit                # 设置 Ctrl+d 为退出 PowerShell
Set-PSReadLineKeyHandler -Key "Ctrl+z" -Function Undo                  # 设置 Ctrl+z 为撤销
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward  # 设置向上键为后向搜索历史记录
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward # 设置向下键为前向搜索历史纪录
# --- ps-read-line -----------------------------------------------------

# --- 引入 ps-PSCompletions ----------------------------------------------
# 补全模块
# 官网: https://pscompletions.abgox.com
# Github: https://github.com/abgox/PSCompletions
# Gitee: https://gitee.com/abgox/PSCompletions
# 一个补全管理模块，它能让你在 PowerShell 中更简单、更方便地使用命令补全。
Import-Module PSCompletions
# https://github.com/abgox/PSCompletions
# 模块版本日志:
#   Github: https://github.com/abgox/PSCompletions/blob/main/module/CHANGELOG.zh-CN.md
#   Gitee : https://gitee.com/abgox/PSCompletions/blob/main/module/CHANGELOG.zh-CN.md
# PSCompletions 命令简单, 只需要输入 psc 并按下 空格 和 Tab 键, 通过补全提示信息，你会快速了解所有命令用法。
# PSCompletions 拥有一个强大的补全菜单，以下是相关的按键绑定:
#   - 选用当前选中的补全项: Enter (回车) | Space (空格)
#       - 当只有一个补全项时，也可以使用 Tab
#   - 删除过滤字符: Backspace (退格)
#   - 退出补全菜单: Esc | Ctrl + c
#       - 当过滤区域没有字符时，也可以使用 Backspace (退格) 退出补全菜单
#   - 选择上一个补全项:  Up  | Left  | Shift + Tab | Ctrl + u | Ctrl + p
#   - 选择下一个补全项: Down | Right |     Tab     | Ctrl + d | Ctrl + n
# PSCompletions 模块只会占用两个全局命名
#   PSCompletions: 函数名, 模块导出的核心函数 (psc 其实就是它的别名)
#  $PSCompletions: 变量名, 存储模块相关的所有数据 (你不能修改它)
# 更多相关信息, 请访问:
#   Website : https://pscompletions.abgox.com
#   Github  : https://github.com/abgox/PSCompletions
#   Gitee   : https://gitee.com/abgox/PSCompletions
# 如果有使用问题, 请提交 issue: https://github.com/abgox/PSCompletions/issues
# 如果 PSCompletions 对你有所帮助, 请给这个项目一个 Star
# PSCompletions 远程仓库更新:
# 新增补全: git 7z arch b2sum b3sum base32 base64 basename basenc bun cargo chfs choco cksum comm conda csplit cut date dd deno df dircolors dirname docker du env factor fmt fnm fold hashsum head jj join kubectl link ln md5sum mise mktemp ngrok nl npm nproc nrm numfmt nvm od oh-my-posh paste pdm pip pnpm powershell psc pwsh python scoop scoop-install scoop-update sfsu uv volta winget wsh wsl wt yarn
# 使用 psc add <completion> 进行添加

# 你可以运行命令 psc config enable_completions_update 0 隐藏这个远程仓库状态提示。
# 但是不建议你这样做, 它是一个很恰当的提示
# --- ps-PSCompletions -----------------------------------------------------

# --- PSFzf 模块配置 ----------------------------------------------------
# [GitHub - kelleyma49/PSFzf: A PowerShell wrapper around the fuzzy finder fzf](https://github.com/kelleyma49/PSFzf)
## 安装 Install-Module PSFzf -Scope CurrentUser
## 安装旧版本：Install-Module -Name PSFzf -RequiredVersion 2.0.0
## 导入 PSFzf
# Import-Module PSFzf
# 设置变量值
if($(which "fd")) {
    # $env:FZF_DEFAULT_COMMAND = "fd --type f --hidden  --absolute-path --exclude .git"
    $env:FZF_DEFAULT_COMMAND = "fd  --hidden  --absolute-path --exclude .git"
}
if ($OsVersion -eq 7) {
    # win7 不支持--height特性
    # $env:FZF_DEFAULT_OPTS ="--ansi --layout=reverse --inline-info"
    $configString = "--ansi --layout=reverse --inline-info"
} else {
    # 设置 fzf 预览命令 预览命令 fzf 默认会过滤控制字符，需通过 --ansi 参数允许原始输出 ,确保预览命令透传 Sixel 数据
    # $env:FZF_DEFAULT_OPTS = "--ansi --preview 'chafa -f sixel --size 80x40 {}'"
    # $env:FZF_DEFAULT_OPTS = "--ansi --preview  'powershell.exe  -ExecutionPolicy Bypass -File $ProjectRoot\scripts\bin\preview.ps1  $([char]34){}$([char]34)' "
    # $env:FZF_DEFAULT_OPTS = "--ansi --preview  'powershell.exe -Command $ProjectRoot\scripts\bin\preview.ps1  $([char]34){}$([char]34)' "
    # $env:FZF_DEFAULT_OPTS = "--ansi --preview  'powershell.exe -Command $ProjectRoot\scripts\bin\FileAndFolderLook.ps1 -Test $([char]34){}$([char]34)' "
    # $env:FZF_DEFAULT_OPTS = "--ansi --layout=reverse --inline-info --height=50%  --preview  'powershell.exe -Command $ProjectRoot\scripts\bin\preview.ps1  $([char]34){}$([char]34)' "
    # $configString = "--ansi --layout=reverse --inline-info --height=50% --reverse"
    $configString = "--ansi --layout=reverse --inline-info --height=60%  "
    if($(which "chafa")) {
        # $configString_preview = "--preview 'powershell.exe -Command $ProjectRoot\scripts\bin\FileAndFolderLook.ps1  $([char]34){}$([char]34)'"
        # $configString_preview = "--preview 'powershell.exe -Command $ProjectRoot\scripts\bin\FileAndFolderLook.ps1  `{`} ' "
        $configString_preview = "--preview 'powershell.exe -Command $ProjectRoot\scripts\bin\FileAndFolderLook.ps1  -InputPath \`"{}\`" ' " # 加单引号 防止路径中有空格
        # $configString_preview = "--preview 'echo {} | powershell.exe -Command $ProjectRoot\scripts\bin\FileAndFolderLook.ps1  ' " # 使用管道方式接收
        $configString = "$configString`  $configString_preview"
        # $configString = "--ansi --layout=reverse --inline-info --height=50% --preview 'echo {} | powershell.exe -Command $ProjectRoot\scripts\bin\FileAndFolderLook.ps1  -InputPath '"
        $configString_bind = "--preview-window=right:40%:border-sharp"
        $configString = "$configString`  $configString_bind"
        $configString_bind = "--bind 'ctrl-l:change-preview-window(right|left|up|down)'"
        $configString = "$configString`  $configString_bind"
        $configString_bind = "--bind 'ctrl-p:toggle-preview'"
        $configString = "$configString`  $configString_bind"
        $configString_bind = "--bind 'ctrl-s:toggle-sort'"  # 切换排序顺序
        $configString = "$configString`  $configString_bind"
        # $configString_bind = "--bind 'ctrl-r:reload(your_refresh_command)'"  # 动态刷新列表
        # $configString = "$configString`  $configString_bind"
        $configString_prompt ="--prompt 'ctrl-l/p/s change/toggle/sort >'" 
        $configString = "$configString`  $configString_prompt"
    }
    # $env:FZF_DEFAULT_OPTS = $configString
}
$env:FZF_DEFAULT_OPTS = $configString
# 初始时打开历史目录选择
# Set-Location (Get-ChildItem . -Recurse | ? { $_.PSIsContainer } | Invoke-Fzf)
# 启用选项卡扩展支持
# Set-PSFzfOption -TabExpansion

#Set-PSReadLineKeyHandler -Key Tab -ScriptBlock { Invoke-FzfTabCompletion }     ## 使用fzf作为Tab补全菜单
Set-PSReadLineKeyHandler -Key "Ctrl+d" -ScriptBlock { Invoke-FzfTabCompletion } ## 使用fzf作为Tab补全菜单

# example command - use $Location with a different command:
#$commandOverride = [ScriptBlock]{ param($Location) Write-Host $Location }
# pass your override to PSFzf:
#Set-PsFzfOption -AltCCommand $commandOverride

## 用您喜欢的绑定替换 'Ctrl+t' 和 'Ctrl+r'：Ctrl+r默认通过 PSReadline 历史反向搜索
## 设置 PsFzf 的历史记录和文件查找器键盘快捷键
#Set-PSFzfOption -PSReadlineChordProvider 'Ctrl+t' -PSReadlineChordReverseHistory 'Ctrl+r'
# --- PSFzf --- ----------------------------------------------------
#------------------------------- Import Modules END   -------------------------------

#------------------------------- TUI Software BEGIN   -------------------------------
# --- fzf 配置 -------------------------------------------------------

# 使用cd fd fzf 查找与切换目录
function  cdf {
    # cd $(fd -t d  | fzf )
    # 管道传入fzf出现中文乱码
    # 取巧办法 控制面板-> 区域 -> 设置UTF-8
    #fdfzf | cd
    # 需要建立一个fdfzf.bat脚本 内容为 fd -t d | fzf 并将其加入系统环境变量中
     
    # PSFzf下
     Get-ChildItem . -Recurse -Attributes Directory | Invoke-Fzf | Set-Location
}


# --- fzf    -------------------------------------------------------

# --- z.lua 模块配置 ------------------------------------------------
# 安装z.lua : scoop install z.lua (如果中间安装失败，去 用户目录下的 C:\Users\用户名\scoop/app/z.lua)
Invoke-Expression -Command (& { (lua C:\Tools\z.lua\z.lua --init powershell) -join "`n" })
# z.lua 快捷用法
function  zh() { z -I -t . } # 回到历史路径，用 fzf 进行历史路径操作
function  zi() { z -i      } # 使用交互式选择模式
function  zl() { z -l      } # 使用 fzf 对多个结果进行选择
# --- z.lua  -------------------------------------------------------

# --- yazi 配置-----------------------------------------------------
# $env:YAZI_LOG = "debug";  # 开启调试模式
$env:RUST_BACKTRACE = 1; 
$env:YAZI_FILE_ONE = "C:\Program Files\Git\usr\bin\file.exe"
$env:YAZI_CONFIG_HOME = "$HOME\AppData\Roaming\yazi"
# $env:YAZI_CONFIG_HOME = "$ProjectRoot\yazi\config"
$env:EDITOR = "vim"
# 设置退出 Yazi 时更改当前工作目录
# function y {
function ExitYaziChangePath {
    $tmp = [System.IO.Path]::GetTempFileName()
    yazi $args --cwd-file="$tmp"
    $cwd = (Get-Content -Path $tmp -Encoding UTF8).Trim()
    $cwd = $cwd -replace "`r|`n", "" 
    if (-not [String]::IsNullOrEmpty($cwd) -and $cwd -ne $PWD.Path -and (Test-Path $cwd)) {
        Set-Location -LiteralPath $cwd
    } else {
        Write-Host "Invalid or unchanged CWD: $cwd"
    }
    Remove-Item -Path $tmp
}

# 使用fzf和yazi交互选择z.lua、zoxide目录
function zy {
    # PowerShell默认的输出编码可能是ASCII或者UTF-16，而fzf或者预览命令使用的可能是另一种编码，比如UTF-8。当编码不匹配时，非ASCII字符（如中文）就会显示为乱码。
    # 设置输出编码为UTF-8
    $originalOutputEncoding = $OutputEncoding
    $OutputEncoding = [System.Text.Encoding]::UTF8
    # 获取所有候选路径：zoxide 历史 + 实时搜索
    $dir = @(
        # 获取 z.lua 历史目录（提取最后一列路径）
        z -l | ForEach-Object { 
            $parts = $_ -split '\s+'
            $parts[-1] 
        }
        # 获取zoxide的目录
        zoxide query -l
        # 实时搜索 (需要 fd)
        # if (Get-Command fd -ErrorAction SilentlyContinue) {
        #       fd --type d --hidden --exclude .git --base-directory ~
        # }
    ) | Sort-Object -Unique | fzf `
      --reverse `
      --prompt "Skip to... > " `
      --preview "powershell.exe -Command $ProjectRoot\scripts\bin\FileAndFolderLook.ps1  -InputPath \`"{}\`" "
    #   --preview  "powershell.exe -NoProfile -Command Get-ChildItem '{}'"
    # 恢复原始编码设置
    $OutputEncoding = $originalOutputEncoding
    if ($dir) { 
      # 处理 WSL 路径转换（如需要）
      if ($dir -match '^/wsl\.?/') {
        $dir = $dir -replace '^/wsl\.?/', '/'
      }
        #   yazi $dir 
        ExitYaziChangePath $dir 
    }
}
# --- yazi   -------------------------------------------------------

# --- lf 配置-------------------------------------------------------
# --- lf       -----------------------------------------------------
#------------------------------- TUI Software  END    -------------------------------

#-------------------------------    Set Funtion BEGIN -------------------------------
function Start-GitBash {
    # & "C:\Program Files\Git\bin\bash.exe" --login -i #启动交互式 Bash ; --login -i 参数确保加载 .bashrc 或 .bash_profile
    
    # 使用 git-for-windows 的完整工具链
    $env:Path = "C:\Program Files\Git\usr\bin;C:\Program Files\Git\mingw64\bin;" + $env:Path
}
Set-Alias gitbash Start-GitBash

## 打开当前终端所在文件夹
function OpenCurrentFolder { # d
	param
	(
		# 输入要打开的路径
		# 用法示例：open C:\
		# 默认路径：当前工作文件夹
		$Path = '.'
	)
	Invoke-Item $Path
}

## git日志美化
function GitLogPretty {
    git fetch
    git log --graph --pretty='%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --all
}

## 终端命令行查英语单词
function fanyi {
    declare q="$*";
    #curl --user-agent curl "https://v2en.co/${q// /%20}";
    curl --user-agent curl "https://d.supjohn.com/${q// /%20}";
}

## 数列形式展示文件
function ShowFiles {
    Param ([int]$c = 5)
    ls | Format-Wide -Column $c -Property Name
}

# 快闪切换git仓库目录
function FzfFindChangGitPath{
    # PowerShell默认的输出编码可能是ASCII或者UTF-16，而fzf或者预览命令使用的可能是另一种编码，比如UTF-8。当编码不匹配时，非ASCII字符（如中文）就会显示为乱码。
    # 设置输出编码为UTF-8
    $originalOutputEncoding = $OutputEncoding
    $OutputEncoding = [System.Text.Encoding]::UTF8
    if ($OsVersion -eq 7) {
        # 获取所有候选路径：zoxide 历史 + fd实时搜索
        $dir = Get-ChildItem -Path "$HOME/Documents" -Depth 9 -Recurse -Force -Filter .git -Directory -ErrorAction SilentlyContinue |
        Where-Object { $_.FullName -notmatch 'node_modules' } | # 排除含 node_modules 的路径
        ForEach-Object { $_.Parent.FullName } | 
        Sort-Object -Unique | fzf `
        --prompt "Skip to... > " `
        --preview  "powershell.exe -NoProfile -Command Get-ChildItem \`"{}\`" " `
        --reverse
    } else {
        # 获取所有候选路径：zoxide 历史 + fd实时搜索
        $dir = @(
            # 
            if ($(which "fd")) {
                # 实时搜索 (需要 fd)
                if (Get-Command fd -ErrorAction SilentlyContinue) {
                    # fd --type d --hidden --exclude .git --base-directory $HOME
                    fd --hidden --type d --full-path "\\.git$" --base-directory $HOME --absolute-path | 
                    ForEach-Object { Split-Path $_ -Parent } # 去除.git 取父一级路径
                }
            } else {
                # Get-ChildItem -Path ./ -Recurse -Force -Filter .git -Directory | 
                # ForEach-Object { $_.Parent.FullName }
                # Get-ChildItem -Path "$HOME/Documents" -Depth 5 -Recurse -Force -Filter .git -Directory -ErrorAction SilentlyContinue |
                Get-ChildItem -Path "$HOME/Documents" -Depth 9 -Recurse -Force -Filter .git -Directory -ErrorAction SilentlyContinue |
                 Where-Object { $_.FullName -notmatch 'node_modules' } | # 排除含 node_modules 的路径
                 ForEach-Object { $_.Parent.FullName } # 提取输出中要的部分的
            }
        ) | Sort-Object -Unique | fzf `
            --prompt "Skip to... > " `
            --preview  "powershell.exe -NoProfile -Command Get-ChildItem '{}'" `
            --reverse
            Write-Host "dir = $dir"
    }
    # 恢复原始编码设置
    $OutputEncoding = $originalOutputEncoding
    # fzf 默认在 cmd 环境下执行预览命令，而 Get-ChildItem 是 PowerShell 独有的命令
    Write-Host "dir = $dir"
    if ($dir) { # 有选择
        # 处理 WSL 路径转换（如需要）
        if ($dir -match '^/wsl\.?/') {
            $dir = $dir -replace '^/wsl\.?/', '/'
        } 
        cd $dir
    }
    
}

# 使用fzf在终端快闪搜索文件，并快速打开文件所在父目录
function FindAndOpenFatherFolder{
	param
	(
		# 输入要打开的路径
		# 用法示例：open C:\
		# 默认路径：当前工作文件夹
		$SearchPath = '.'
	)
    # $env:WINPTY_DEBUG = "1"
    # $env:TERM = "xterm-256color"
    # PowerShell默认的输出编码可能是ASCII或者UTF-16，而fzf或者预览命令使用的可能是另一种编码，比如UTF-8。当编码不匹配时，非ASCII字符（如中文）就会显示为乱码。
    # 设置输出编码为UTF-8
    $originalOutputEncoding = $OutputEncoding
    $OutputEncoding = [System.Text.Encoding]::UTF8
    Write-Host "SearchPath = $SearchPath"
    $filePath = @(
        fd --absolute-path --base-directory $SearchPath 
    # )| Sort-Object -Unique | fzf  `
    # --prompt "Find ... > " `
    # --ansi `
    # --preview  "chafa  -f sixel --size 80x40 $([char]34){}$([char]34)" `
    # --reverse
    )| Sort-Object -Unique | fzf  `
        --prompt "Find ... > " `
        --ansi `
        --preview  "powershell.exe  -ExecutionPolicy Bypass -File $ProjectRoot\scripts\bin\FileAndFolderLook.ps1 \`"{}\`" " `
        --reverse
        # --preview  "powershell.exe  -ExecutionPolicy Bypass -File $ProjectRoot\scripts\bin\preview.ps1 $([char]34){}$([char]34)" `
    # 恢复原始编码设置 
    $OutputEncoding = $originalOutputEncoding
    if ($filePath) { # 选择了后
        # # 使用Split-Path安全获取父目录
        # $fileFatherPath = Split-Path $filePath -Parent
        # Write-Host "fileFatherPath = $fileFatherPath"
        # # 打开文件所在父级目录
        # Invoke-Item $fileFatherPath

        # 使用资源管理器的选中功能
        Start-Process explorer.exe -ArgumentList "/select,`"$filePath`""
        
    }

}

# 快打开查找git仓库
function OpenLazyOrGitui{
    # 判断当前是否是git仓库，不是则打开 fzf命令让快闪跳转
    # PowerShell默认的输出编码可能是ASCII或者UTF-16，而fzf或者预览命令使用的可能是另一种编码，比如UTF-8。当编码不匹配时，非ASCII字符（如中文）就会显示为乱码。
    # 设置输出编码为UTF-8
    $originalOutputEncoding = $OutputEncoding
    $OutputEncoding = [System.Text.Encoding]::UTF8 
    # 检查是否在 Git 仓库中
    if (-not (git rev-parse --is-inside-work-tree 2>$null)) {
        # Write-Error "当前不在 Git 仓库中"
        Write-Host "Not currently in the Git repository"
        # 获取所有候选路径：zoxide 历史 + fd实时搜索
        $dir = @(
            # 
            # if ($(which "fd")) {
            #     # 实时搜索 (需要 fd)
            #     if (Get-Command fd -ErrorAction SilentlyContinue) {
            #         # fd --type d --hidden --exclude .git --base-directory $HOME
            #         fd --hidden --type d --full-path "\\.git$" --base-directory $HOME --absolute-path | 
            #         ForEach-Object { Split-Path $_ -Parent } # 去除.git 取父一级路径
            #     }
            # } else {
                # Get-ChildItem -Path ./ -Recurse -Force -Filter .git -Directory | 
                # ForEach-Object { $_.Parent.FullName }
                # Get-ChildItem -Path "$HOME/Documents" -Depth 5 -Recurse -Force -Filter .git -Directory -ErrorAction SilentlyContinue |
                Get-ChildItem -Path "$HOME/Documents" -Depth 9 -Recurse -Force -Filter .git -Directory -ErrorAction SilentlyContinue |
                 Where-Object { $_.FullName -notmatch 'node_modules' } | # 排除含 node_modules 的路径
                 ForEach-Object { $_.Parent.FullName } # 提取输出中要的部分的
            # }
        ) | Sort-Object -Unique | fzf `
        --prompt "Skip to... > " `
        --preview  "powershell.exe  -ExecutionPolicy Bypass -File $ProjectRoot\scripts\bin\FileAndFolderLook.ps1 \`"{}\`" " `
        --reverse
        # --preview  "powershell.exe -NoProfile -Command Get-ChildItem \`"{}\`" " `
        # 恢复原始编码设置
        $OutputEncoding = $originalOutputEncoding
        Write-Host "dir = $dir"
        if ($dir) { 
            # 处理 WSL 路径转换（如需要）
            if ($dir -match '^/wsl\.?/') {
                $dir = $dir -replace '^/wsl\.?/', '/'
            }  
            cd $dir
        }
        
    } 
    # 
    if (git rev-parse --is-inside-work-tree 2>$null) {
        # 是git 仓库地址
        if($(which "lazygit")){
            lazygit
        } elseif($(which "lazygit")){
            gitui
        } elseif($(which "lazygit")){
            GitAddToggle
        } else{
            Write-Host "Not lazygit、gitui、GitAddToggle"
        }
    }
}

# 注意：一些命令 如：tree
# 在 PowerShell 中执行 tree /F > a.txt 导致中文乱码的原因是 编码不一致。
# PowerShell 默认使用 UTF-16 编码输出重定向内容，而 tree 命令生成的文本是基于系统默认的代码页（如中文系统下的 GBK 或 CP936）。两者的编码冲突会导致文本文件中的中文显示为乱码。
# 解决方法：
    # 方法 1：使用 cmd 执行命令
        # 直接在 cmd 环境下运行命令，避免 PowerShell 的编码干扰：
        # cmd /c "tree /F > a.txt"
        # 注意需要切换盘，跨盘会提示无法找到路径
        # cmd /c "tree  /F >  ..\eBookesList.txt"
        # 此时生成的 a.txt 会使用系统默认编码（如 GBK），中文正常显示。
#     # 验证结果
#         # 用支持多编码的文本编辑器（如 Notepad++、VS Code）打开 a.txt，确保选择正确的编码（如 GBK 或 ANSI）。

# function Get-PSFormatTree {
#     param($Path = ".")
#     $stack = Get-Item $Path
#     while ($stack.Count -gt 0) {
#         $current = $stack[-1]
#         $stack = $stack[0..($stack.Count-2)]
#         $depth = ($current.FullName -split '[\\/]').Count - ($Path -split '[\\/]').Count
#         $indent = '│   ' * ($depth - 1) + '├── '
#         if ($depth -eq 0) { $indent = '' }
#         $current.FullName.Replace($Path, '').TrimStart('\')
#         Get-ChildItem $current.FullName | ForEach-Object {
#             if ($_.PSIsContainer) {
#                 $stack += $_
#                 "$indent📂 $($_.Name)"
#             } else {
#                 "$indent📄 $($_.Name)"
#             }
#         }
#     }
# }
# Get-PSFormatTree F:\XLocalData\X5eBookes | Out-File -Encoding UTF8 ~/Desktop/eBookesList.md
#-------------------------------    Set Funtion END   -------------------------------

#-------------------------------    Set Alias BEGIN     -------------------------------
function initEnv2 {
    param(
        [Parameter(Mandatory=$false)]
        [switch]$Test,  # 测试模式（详细日志）

        [Parameter(Mandatory=$false)]
        [string]$DiySoftware=$null,  # 指定要安装的软件（多个用逗号分隔）

        [Parameter(Mandatory=$false)]
        [switch]$All,   # 自动安装所有软件
        
        [Parameter(Mandatory=$false)]
        [string]$OutputSavePath = "${env:USERPROFILE}\Downloads\WinSoftwares"  # 输出保存地址
    )
    # powershell.exe  "$ProjectRoot\windows-terminal\initEnv-V2.ps1" -DiySoftware $DiySoftware
    # 方法1：直接调用（同进程）
    & "$ProjectRoot\windows-terminal\initEnv-V2.ps1" @PSBoundParameters
}

Set-Alias -Name open -Value OpenCurrentFolder     # 打开当前终端所在文件夹 
Set-Alias -Name lsc -Value ShowFiles              # 数列形式展示文件 
Set-Alias -Name glp -Value GitLogPretty           # git日志美化 
Set-Alias -Name fy -Value GitLogPretty            # 终端命令行查英语单词
Set-Alias -Name ranger -Value zy                  # 
Set-Alias -Name y -Value zy                       # 
# Set-Alias -Name fga -Value GitAddToggle           # 
function fga {
    powershell.exe -ExecutionPolicy Bypass -File "$ProjectRoot\scripts\bin\Xgit.ps1" -ParamValue fa
}
Set-Alias -Name l -Value OpenLazyOrGitui           # 
Set-Alias -Name lg -Value lazygit          # 
Set-Alias -Name fg -Value FzfFindChangGitPath          # 
Set-Alias -Name fo -Value FindAndOpenFatherFolder  # 使用fd fzf组合快速搜索与打开文件所在目录
#-------------------------------    Set Alias END     -------------------------------

